package cn.mickey.exchange.api;

import cn.hutool.core.util.IdUtil;
import cn.mickey.exchange.annotation.LoginUser;
import cn.mickey.exchange.annotation.RedisCache;
import cn.mickey.exchange.domain.JsonResponse;
import cn.mickey.exchange.domain.model.OrderModel;
import cn.mickey.exchange.domain.model.UserModel;
import cn.mickey.exchange.service.OrderService;
import cn.mickey.exchange.handler.OrderTaskHandler;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@RedisCache
@RestController
@RequestMapping("/order")
public class OrderApi {

    @Resource
    private OrderService orderService;

    @PostMapping("/add")
    public JsonResponse addOrder(@LoginUser UserModel user,
                                 @RequestBody OrderModel orderModel) {
        if (OrderTaskHandler.orderService == null) {
            OrderTaskHandler.orderService = orderService;
        }
        orderModel.setOrderNumber(IdUtil.getSnowflake().nextIdStr())
                .setCreateTime(LocalDateTime.now())
                .setUserId(user.getUserId())
                .setOrderStatus((byte) 0)
                .setPaymentStatus((byte) 0);
        if (orderService.addOrder(orderModel)) {
            return JsonResponse.success(orderModel);
        }
        return JsonResponse.fail("系统错误!");
    }

    @PostMapping("/update")
    public JsonResponse updateOrder(@RequestBody OrderModel orderModel) {
        if (orderModel.getPaymentStatus() !=null && orderModel.getPaymentStatus() == (byte)1) {
            orderModel.setPaymentTime(LocalDateTime.now());
        }
        if (orderService.updateOrder(orderModel)) {
            return JsonResponse.success(orderModel);
        }
        return JsonResponse.fail("系统错误!");
    }

    @GetMapping("/my")
    public JsonResponse getMyOrder(@LoginUser UserModel user) {
        return JsonResponse.success(orderService.getMyOrder(user.getUserId()));
    }

    @GetMapping("/my-sold")
    public JsonResponse getMySoldIdle(@LoginUser UserModel user) {
        return JsonResponse.success(orderService.getMySoldIdle(user.getUserId()));
    }

    @GetMapping("/info")
    public JsonResponse getOrderInfo(@LoginUser UserModel user,
                                     @RequestParam Long id) {
        OrderModel orderModel = orderService.getOrder(id);
        if (orderModel.getUserId().equals(user.getUserId()) ||
                orderModel.getIdleItem().getUserId().equals(user.getUserId())) {
            return JsonResponse.success(orderModel);
        }
        return JsonResponse.fail("系统错误");
    }
}
